var MongoDB = require('mongodb').Db;
var Server = require('mongodb').Server;
var moment = require('moment');

/*
 ESTABLISH DATABASE CONNECTION
 */

var dbName = process.env.DB_NAME || 'node-login';
var dbHost = process.env.DB_HOST || 'localhost';
var dbPort = process.env.DB_PORT || 27017;

var db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});
db.open(function (e, d) {
    if (e) {
        console.log(e);
    } else {
        if (process.env.NODE_ENV == 'live') {
            db.authenticate(process.env.DB_USER, process.env.DB_PASS, function (e, res) {
                if (e) {
                    console.log('mongo :: error: not authenticated', e);
                }
                else {
                    console.log('mongo :: authenticated and connected to database :: "' + dbName + '"');
                }
            });
        } else {
            console.log('mongo :: connected to database :: "' + dbName + '"');
        }
    }
});

var reservations = db.collection('reservations');


exports.updateReservation = function (newData, callback) {
    console.log('--------updateReservation---------');

    var findQuery = {'hash_user': newData['hash_user'], 'start': newData.start, 'end': newData.end}; //查找是否当前用户已经提交， 避免重复
    console.log("findQuery: " + findQuery['hash_user']);
    var result = {};
    reservations.update({"id": newData.id}, {$set: newData}, {upsert: true}, function (err, res) {
        console.log('update --- err' + err);
        if (err) {
            result['id'] = 2;
            result['msg'] = "预约失败";
            callback(result);
        } else {
            result['id'] = 1;
            result['msg'] = "预约成功";
            callback(result);
        }
    });
};


//检查预约是否存在
function isReservationExists(findQuery, callback) {
    console.log(' --- isReservationExists ---');

    reservations.count(findQuery, function (err, count) {
        console.log("err: " + err);
        console.log("count: " + count);
        var res = {};
        if (count > 0) {//如果有   1 - 重复提交 2 - 提交失败
            res['id'] = 4;
            res['msg'] = "预约已存在, 不要重复提交";
            callback(res);
        } else {
            res['id'] = 0;
            res['msg'] = "预约不存在";
            callback(res);
        }
    });

}

//更新预约状态
exports.updateReservationStatus = function (updateData, callback) {
    var res = {};
    reservations.update({"id": updateData.id}, {$set: {'status': updateData.status}}, function (err, result) {
        if (err) {
            res['id'] = 2;
            callback(res);
        } else {
            res['id'] = 1;
            callback(res);
        }
    });
};


exports.findRoomReservation = function (findQuery, callback) {
    console.log(' --- findRoomReservation ---');
    var roomId = findQuery['room_id'];
    var start = findQuery['start'];
    var end = findQuery['end'];
    var hashUser = findQuery['hash_user'];

    //查找是否当前用户已经提交， 避免重复
    isReservationExists({'hash_user': hashUser, 'start': start, 'end': end}, function (result) {
        if (result.id == 0) { //不存在
            // var totalCount;
            // reservations.count(function (err, count) {
            //     totalCount = count;
            //     console.log('totalCount: ' + totalCount);
            // });
            // reservations.count({
            //     $or: [{'room_id': roomId, 'end': {$lt: start}}, {
            //         'room_id': roomId, 'start': {$gt: end}
            //     }]
            // }, function (err, count) {
            //     console.log(' ----- count  err ---- ' + err);
            //     if (count == totalCount) { //如果没有时间冲突
            //         result['id'] = 1; //没有时间冲突
            //         callback(res);
            //     } else { //可能有时间冲突
            //         reservations.find({
            //             $or: [
            //                 {'room_id': roomId, 'end': {$gte: end}, 'start': {$lte: end}},
            //                 {'room_id': roomId, 'end': {$gte: start}, 'start': {$lte: start}},
            //             ]
            //             // 'room_id': roomId, 'start': {$gte: start}, 'end': {$lte: end}
            //         }).toArray(function (err, res) {
            //             console.log("find err: " + err);
            //             if (res.length == 0) { //没有时间冲突
            //                 result['id'] = 1;
            //                 result['msg'] = '没有时间冲突';
            //                 callback(result);
            //
            //             } else {
            //                 // var isConflit = false;
            //
            //                 res.forEach(function (element) {
            //                     console.log(' --- element status --- ', element.status);
            //                     if (Number(element['status']) == 2) {
            //                         result['id'] = 3;  //有时间冲突 ，失败
            //                         result['msg'] = '申请失败\n请选更换申请时间';
            //                         callback(result);
            //                     } else if (Number(element['status']) == 1) {
            //                         result['id'] = 2;  //可能有时间冲突
            //                         result['msg'] = '申请可能失败\n该时间已有其他预约申请，选择继续申请或者修改时间';
            //                     }
            //                     callback(result);
            //                 });
            //             }
            //         });
            //     }
            // });


            reservations.find({
                $or: [
                    {'room_id': roomId, 'start': {$lte: start}, 'end': {$gte: start}},
                    {'room_id': roomId, 'start': {$lte: end}, 'end': {$gte: end}},
                    // {'room_id': roomId, 'start': {$lte: start}, 'end': {$lte: end}},
                    {'room_id': roomId, 'start': {$gte: start}, 'end': {$lte: end}},
                ]
            }).toArray(function (err, res) {
                console.log("find err: " + err);
                console.log("res.length: " + res.length);
                if (res.length == 0) { //没有时间冲突
                    result['id'] = 1;
                    result['msg'] = '没有时间冲突';
                    callback(result);
                } else {
                    var isConflit = false;
                    res.forEach(function (element) {
                        console.log(' --- element status --- ', element.status);
                        if (Number(element['status']) == 2) {

                            isConflit = true;
                            // return element['status'] === 2;
                        }
                        // else if (Number(element['status']) == 1) {
                        //
                        // }
                    });
                    console.log('find result : ' + result.id);
                    if (isConflit) {
                        result['id'] = 3;  //有时间冲突 ，失败
                        result['msg'] = '申请失败,\n请选更换申请时间, 该时间段已有成功的预约。';
                        callback(result);
                    } else {
                        result['id'] = 2;  //可能有时间冲突
                        result['msg'] = '申请可能失败，\n因为该时间已有其他预约申请，选择继续申请或者修改时间。';
                        callback(result);
                    }
                }
            });

        } else { //预约已存在
            callback(result);
        }
    });


};


// exports.findUserName = function (hashUser, callback) {
//     console.log('--------findUserName---------');
//
//     // reservations.insert(newData, {safe: true}, callback);
//     var findQuery = {'hash_user': hashUser};
//     reservations.find(findQuery, function (err, result) {
//         console.log("result: " + result);
//
//         if (result) { //如果有 1 - 用户已存在 2 - 用户不存在
//             callback(1, "用户名已存在");
//         } else {
//             callback(2, "用户名不存在");
//         }
//     });
// };


exports.removeReservation = function (data, callback) {

    // var query = query = {'id': data.id, 'user': data.user};
    // if(data.userType == 1){ //如果是管理员
        //     query['id'] = data.id;
        // }else {
        //     query['id'] = data.id;
        //     query['user'] = data.user;
        // }



    var query = data.userType == 1 ? {'id': String(data.id)} : {'id': String(data.id), 'user': data.user};

    var result = {};
    console.log('query.id ------ ' + query.id);
    reservations.remove(query, function (err, res) {
        console.log('remove err ' + err);
        console.log('remove res ' + res);
        if(err){
            result['id'] = 2;
            result['msg'] = '删除失败';
        }else{
            result['id'] = 1;
            result['msg'] = '删除成功';
        }
        callback(result);
    });

};

//按会议室查找预约列表
exports.getAllReservations = function (query, callback) {
    reservations.find(query).toArray(function (e, res) {
            if (e)
                callback(e)
            else
                callback(null, res)
        }
    );
};

//查询一个预约
exports.getOneReservation = function (query, callback) {
    console.log("query :", query);
    var result = {};
    reservations.findOne(query, function (e, res) {
        if (e){
            result['id'] = 2;
            result['data'] = null;
        }else{
            result['id'] = 1;
            result['data'] = res;
        }
        callback(result);
    });
};

//admin operate database
exports.delRecord = function (newData, callback) {
    reservations.findOne({id: newData.id}, function (e, o) {
        if (o) {
            reservations.remove({id: newData.id}, callback);
        } else {
            callback(true, null);
        }
    })
};

exports.delAllRecords = function (callback) {
    reservations.remove({}, callback);
};


/* private encryption & validation methods */
